package com.gexin.model.system;

import com.gexin.common.cache.CacheUtils;
import com.gexin.common.cache.EhcacheKeyConst;
import com.gexin.common.cache.RedisKeyConst;
import com.gexin.model.system.base.BaseAddrProvinces;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 业务名称:  t_addr_provinces(省份信息表) 
 */
@SuppressWarnings("serial")
public class AddrProvinces extends BaseAddrProvinces<AddrProvinces> {
	public static final AddrProvinces dao = new AddrProvinces();

	/**
	 * 查询所有省份
	 * @return
	 */
	public List<AddrProvinces> getProvinces() {
		return dao.find("select * from t_addr_provinces order by provinceid");
	}

	/**
	 * fang   2016-07-06
	 * 拼凑ztree的方法
	 *  id:1, pId:0, name:"湖北省",isParent:true
	 */
	public List<Object>  getAddrZtree(){

		List<Object>  tree_list = CacheUtils.get(RedisKeyConst.Address_Ztree_All);
		if(tree_list==null){
			//先初始化
			tree_list=new ArrayList<Object>();
			//先增加省
			List<AddrProvinces> province_list= AddrProvinces.dao.cache_getAllProvince();
			for( AddrProvinces province :province_list ){
				tree_list.add(createZtreeMap(province.getProvinceid(), "0", province.getProvince()));
			}
			//再增加市
			List<AddrCities> city_list= AddrCities.dao.cache_getAllCities();
			for(AddrCities city:city_list  ){
				tree_list.add(createZtreeMap(city.getCityid(), city.getProvinceid(), city.getCity()));
			}
			List<AddrAreas> area_list= AddrAreas.dao.getAllAreas();
			for( AddrAreas area:area_list    ){
				tree_list.add(createZtreeMap(area.getAreaid(), area.getCityid(), area.getArea()));
			}
			CacheUtils.set(RedisKeyConst.Address_Ztree_All, tree_list,365*24*3600);//缓存一年
		}
		//List<Object> tree_list=new ArrayList<Object>();
		//再增加区/县
		//return  JsonKit.toJson(tree_list);
		return  tree_list;
	}



	/**
	 * 构建map
	 * fang  2016-07-06
	 */
	public HashMap<String, String> createZtreeMap(String val1, String val2, String val3){
		HashMap<String, String> map=new HashMap<String, String>();
		map.put("id", val1);
		map.put("pId", val2);
		map.put("name", val3);
		return map;
	}


	/**
	 * fang  2016-07-06
	 * 拿到所有的省份
	 */
	/*public List<AddrProvinces> getAllProvince(){
		String sql=" select *  from t_addr_provinces order by id asc";
		return dao.find(sql);
	}*/
	/**
	 * 缓存
	 * @return
	 */
	public List<AddrProvinces>cache_getAllProvince(){
		//CacheUtils.del(RedisKeyConst.Address_Province);
		List<AddrProvinces>  province_list = CacheUtils.getEhcache(EhcacheKeyConst.OneDay,"Address_Province1");
		if(province_list==null){
			province_list=dao.find("select *,provinceid as province_id  from t_addr_provinces order by id asc");
			CacheUtils.setEhcache(EhcacheKeyConst.OneDay,"Address_Province1", province_list);//缓存一年
		}
		return province_list;
	}

	public AddrProvinces getProvinceByProvincedId(String province_id){
		String sql=" select *  from t_addr_provinces where provinceid =?";
		return dao.findFirst(sql,province_id);
	}
}
